import datetime

import pymysql
import urllib.request
import json

db = pymysql.connect("114.115.160.16", "root", "123456Aa!", "fund")
cursor = db.cursor()

headers = {
    "token": "atTPd9c8sA"
}

cursor.execute("select max(id) from api_vary")
max_id = cursor.fetchall()[0][0]
if max_id == None:
    max_id = 1
else:
    max_id += 1

sql = "select fund_id,category from api_fund"

cursor.execute(sql)

yesterday = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")

for data in cursor.fetchall():
    fund_id = data[0]
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=" + yesterday, headers=headers)
    response = urllib.request.urlopen(req)
    fund = json.loads(response.read().decode("UTF-8"))
    net_worth = fund["data"]["netWorthData"]

    for worth in net_worth:
        date = worth[0]
        value = worth[1]
        rate = worth[2]
        sql = "insert into api_vary values(%d,'%s',%f,'%s',%f)" % (max_id, fund_id, float(value), date, float(rate))
        cursor.execute(sql)
        print("ok!!", fund_id)
        max_id += 1
db.commit()
print("success")